package com.spring.picture.controller;

import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileResult;
import com.spring.picture.common.BaseResponse;
import com.spring.picture.common.ResultUtils;
import com.spring.picture.manager.OSSManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URL;

@RestController
@RequestMapping("/file")
public class OSSFileController {

    @Resource
    private OSSManager ossManager;

    @PostMapping("/upload1")
    public BaseResponse<PutObjectResult> upload1(@RequestParam("file") MultipartFile file) throws IOException {
        String key = ossManager.generateKey(file);
        PutObjectResult result = ossManager.putObject(key, file);
        return ResultUtils.success(result);
    }

    @PostMapping("/upload2")
    public BaseResponse<CompleteMultipartUploadResult> upload2(@RequestParam("file") MultipartFile file) throws IOException {
        String key = ossManager.generateKey(file);
        CompleteMultipartUploadResult result = ossManager.completeMultipartUpload(key, file);
        return ResultUtils.success(result);
    }

    @PostMapping("/upload3")
    public BaseResponse<UploadFileResult> upload3(@RequestParam("file") MultipartFile file) throws Throwable {
        String key = ossManager.generateKey(file);
        UploadFileResult result = ossManager.uploadLargeFile(key, file);
        return ResultUtils.success(result);
    }

    @GetMapping("/upload4")
    public BaseResponse<URL> upload4() {
        String key = "user/test.jpg";
        URL url = ossManager.generatePresignedUrl(key);
        return ResultUtils.success(url);
    }
}
